package community.interfaces.controller;

import community.application.service.CommentService;
import community.domain.model.Comment;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/comments")
@RequiredArgsConstructor
public class CommentController {

    private final CommentService commentService;

    @PostMapping
    public Comment create(@RequestBody Comment comment) {
        return commentService.createComment(comment);
    }

    @GetMapping("/{id}")
    public Optional<Comment> getById(@PathVariable Long id) {
        return commentService.getCommentById(id);
    }

    @GetMapping("/post/{postId}")
    public List<Comment> getByPostId(@PathVariable Long postId) {
        List<Comment> comments = commentService.getCommentsByPostId(postId);

        //  触发懒加载，确保 Comment.user 不为 null
        for (Comment comment : comments) {
            if (comment.getUser() != null) {
                comment.getUser().getUsername(); // 触发懒加载
            }
        }
        return comments;
    }


    @GetMapping("/reply/{parentId}")
    public List<Comment> getByParentId(@PathVariable Long parentId) {
        return commentService.getRepliesByParentId(parentId);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        commentService.deleteComment(id);
    }
}
